import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
    Form, Input, InputNumber,Space,
    Button, message, Select, Modal,
    Cascader, TreeSelect, Switch,
    Checkbox, Card, Row, Col, Upload
} from 'antd';
import {
    LoadingOutlined,
    PlusOutlined,
    ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Link, connect } from 'umi';
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
import UploadUtil from '../UploadUtil';

const { confirm } = Modal;

@connect(({ user, CrudModel, Article, Category }) => ({
    currentUser: user.currentUser,
    response: CrudModel.response,
    Article,
    Category,
}))
class ContentEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            datas: {},
            cascaderOption: [],
            contentEditor: '',
            imageUrl: '',
            imgList: [],
        }
    }
    formRef = React.createRef();
    componentDidMount() {
        const { Article } = this.props;
        this.fetchCategory();
        console.log(this.props.location.query.id)
        if (this.props.location.query.id) {
            this.getData(this.props.location.query.id);
        }
    }
    getData = (id) => {
        const { dispatch } = this.props;
        if (id > 0) {
            dispatch({
                type: 'CrudModel/get',
                payload: { id },
                control: 'Article',
            }).then(() => {
                var result = this.props.response.result;
                result.contents = BraftEditor.createEditorState(result.contents);
                this.setState({ datas: result });
                if (result.imageUrl) {
                    this.setState({ imageUrl: UploadUtil.imgServ + result.imageUrl });
                }

                this.formRef.current.setFieldsValue({ article: result });
            });
        }
    }
    fetchCategory = () => {
        this.props.dispatch({
            type: 'Category/getTreeData',
            payload: { layout: 'article' }
        }).then(() => {
            this.setState({ cascaderOption: this.props.Category.response.result });
        })
    }
    onFinish = async (values) => {
        var act = "CrudModel/create";
        if (values.article.id > 0) {
            act = "CrudModel/update";
        }
        values.article.contents = this.state.contentEditor;

        if (this.state.imgList && this.state.imgList.length > 0) {
            var pic = await UploadUtil.uploadPic(this.state.imgList, values.article.id, "Article", "imageUrl");
            values.article.imageUrl = pic;
        }

        this.props.dispatch({
            type: act,
            payload: values.article,
            control: 'Article',
        }).then(() => {
            var resp = this.props.response;
            if (resp.success) {
                message.success('保存成功！');
            }
            else {
                message.error('保存错误，请联系管理员');
            }
        });
    };
    ResetForm = () => {
        var data = {
            id: 0,
        }
        this.setState({ datas: data });
        this.formRef.current.resetFields();
    }
    handleDel = () => {
        this.props.dispatch({
            type: "CrudModel/delete",
            payload: { Id: this.state.datas.id },//this.props.response.id
            control: 'Article',
        }).then(() => {
            var resp = this.props.response;
            if (resp.success) {
                message.success('删除成功！');
                this.props.fetchDatas();
                this.formRef.current.resetFields();
            }
            else {
                message.error('删除错误，请联系管理员！');
            }
        })
    }
    showConfirm = () => {
        var _this = this;
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.handleDel();
            },
            onCancel() { },
        });
    }
    handleChange = (editorState) => {
        console.log(editorState.toHTML())
        this.setState({
            contentEditor: editorState.toHTML(),
        });
    }
    handleUpload = info => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            UploadUtil.getBase64(info.file.originFileObj, imageUrl =>
                this.setState({
                    imageUrl,
                    imgList: info.fileList,
                    loading: false,
                }),
            );
        }
    };
    render() {
        const layout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
        };
        const { datas, imageUrl, loading } = this.state;
        const editorProps = {
            height: 120,
            onChange: this.handleChange,
            onRawChange: this.handleRawChange,
        }
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        return (
            <PageHeaderWrapper title={false}>
                <Card title="文章编辑" extra={<Link to="./content">返回列表</Link>}>
                    <Form layout="vertical" ref={this.formRef} onFinish={this.onFinish} >
                        <Row gutter={[30, 16]}>
                            <Col span={14}>
                                <div style={{ display: 'none' }}>
                                    <Form.Item
                                        label="id"
                                        name={['article', 'id']}>
                                        <Input />
                                    </Form.Item>
                                    <Form.Item
                                        label="imageUrl"
                                        name={['article', 'imageUrl']}>
                                        <Input />
                                    </Form.Item>
                                </div>
                                <Form.Item name={['article', 'categoryId']} label="所属分类" rules={[{ required: true, message: "请选择分类" }]}>
                                    <TreeSelect
                                        value={this.state.value}
                                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                        treeData={this.state.cascaderOption}
                                        placeholder="Please select"
                                        treeDefaultExpandAll
                                        onChange={this.onChange}
                                        style={{ width: 300 }}
                                    />
                                </Form.Item>
                                <Form.Item label="标题">
                                    <Input.Group compact>
                                        <Form.Item
                                            noStyle
                                            name={['article', 'title']}
                                            rules={[{ required: true, message: "请输入标题" }]}>
                                            <Input style={{ width: "45%" }} />
                                        </Form.Item>
                                        <Form.Item
                                            noStyle
                                            name={['article', 'subTitle']}>
                                            <Input style={{ width: "55%" }} placeholder="副标题，不超过50字符" />
                                        </Form.Item>
                                    </Input.Group>
                                </Form.Item>
                                <Form.Item
                                    name={['article', 'summary']}
                                    label="概述">
                                    <Input.TextArea />
                                </Form.Item>
                                <Form.Item name={['article', 'contents']} label="内容"
                                    rules={[{ required: true, message: "请输入内容" }]}>
                                    <BraftEditor style={{ border: '1px solid #ccc' }} {...editorProps} />
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item
                                    name={['article', 'tags']}
                                    label="标签">
                                    <Input />
                                </Form.Item>

                                <Form.Item label="图片">
                                    <Upload
                                        name="avatar"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        showUploadList={false}
                                        beforeUpload={UploadUtil.beforeUpload}
                                        onChange={this.handleUpload}
                                    >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                    </Upload>
                                </Form.Item>
                                <Form.Item>
                                    <Input.Group compact>
                                        <Form.Item
                                            name={['article', 'isHot']}
                                            valuePropName="checked">
                                            <Checkbox>热</Checkbox>
                                        </Form.Item>
                                        <Form.Item
                                            name={['article', 'isRec']}
                                            valuePropName="checked">
                                            <Checkbox>推荐</Checkbox>
                                        </Form.Item>
                                        <Form.Item
                                            name={['article', 'isTop']}
                                            valuePropName="checked">
                                            <Checkbox>置顶</Checkbox>
                                        </Form.Item>
                                    </Input.Group>
                                </Form.Item>
                                <Form.Item >
                                    <Space>
                                        <Button
                                            type="primary"
                                            htmlType="submit"
                                            loading={this.state.loading}
                                        >确定</Button>
                                        <Button onClick={this.ResetForm}>重设</Button>
                                        <Button danger
                                            onClick={this.showConfirm}
                                            disabled={datas.id == 0 || !datas.id}>删除</Button>
                                    </Space>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Card>
            </PageHeaderWrapper>
        )
    }
}
export default ContentEdit;